/*
   Copyright 2011 James Bowling

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package com.armedia.dctm.constraints;

import static com.armedia.dctm.constraints.ConstraintUtils.decodeAttributeDataType;

import org.apache.log4j.Logger;

import com.documentum.com.DfClientX;
import com.documentum.com.IDfClientX;
import com.documentum.fc.client.IDfCollection;
import com.documentum.fc.client.IDfQuery;
import com.documentum.fc.client.IDfSession;
import com.documentum.fc.common.DfException;
import com.documentum.fc.common.DfLogger;
import com.documentum.fc.common.IDfValue;

public class DqlUtils {
	
	private static final Logger LOGGER = DfLogger.getLogger(DqlUtils.class);	
		
	public static String getDqlValueLiteral(final IDfValue value) {
		String valueLiteral;
		switch (value.getDataType()) {
		case IDfValue.DF_BOOLEAN:
			valueLiteral = new Boolean(value.asBoolean()).toString();
			break;
		case IDfValue.DF_DOUBLE:
			valueLiteral = value.toString();
			break;
		case IDfValue.DF_ID:
			valueLiteral = "'" + value.toString() + "'";
			break;
		case IDfValue.DF_INTEGER:
			valueLiteral = value.toString();
			break;
		case IDfValue.DF_STRING:
			String stringValue = value.toString();
			valueLiteral = "'" + stringValue.replaceAll("'", "''") + "'";
			break;
		case IDfValue.DF_TIME:
			valueLiteral = "DATE('" + value.toString() + "')";
			break;
		default:
			final String format = "Unhandled switch case for type [%s] with value[%s]";
			final String dataTypeStr = decodeAttributeDataType(value.getDataType());
			final String msg = String.format(format, dataTypeStr, value.toString());
			throw new RuntimeException(msg);
		}			
		return valueLiteral;
	}
	
	public static int executeSelectCountQuery(IDfSession session, String dql) throws DfException {
		LOGGER.debug(dql);
		IDfClientX client = new DfClientX();
		IDfQuery q = client.getQuery();
		q.setDQL(dql);
		int count = 0;
		IDfCollection coll = null;
		try {
			coll = q.execute(session, IDfQuery.READ_QUERY);
			coll.next();
			count = coll.getInt(coll.getAttr(0).getName());
		} finally {
			if (coll != null) {
				coll.close();
				coll = null;
			}
		}
		return count;
	}	

}
